<template>
  <div class="header-with-back">
    <div class="back-nav" @click="goToYRCG">
      <van-icon name="arrow-left" />
      <span style="font-size: 1.2rem">{{title}}</span>
    </div>
  </div>
  <div class="bottom-van" @click="handleOutsideClick">
    <div class="bottom-van-top">
      <div class="content">
        <div class="img-container">
          <!-- 图片信息卡片 -->
          <van-cell-group inset class="video-info">
            <van-cell>
              <template #title>
                <h2 class="video-title">{{item.title}}</h2>
              </template>
            </van-cell>

            <van-cell title="上传人" :value="item.teacherName" />

            <van-cell title="文章" :label="item.content" />
            <van-image
                width="20rem"
                height="15rem "
                fit="contain"
                :src="item.articleImage"
            />
          </van-cell-group>

          <!-- 评论区域 -->
          <van-cell-group inset class="comments" style="margin-bottom: 95px">
            <div class="comment-input-container">
              <van-field
                  v-model="newComment"
                  placeholder="写下你的评论..."
                  :border="false"
              >
                <template #button>
                  <van-button
                      size="small"
                      type="primary"
                      @click="submitComment"
                      :disabled="!newComment.trim()"
                      :loading="commentLoading"
                  >
                    发送
                  </van-button>
                </template>
              </van-field>
            </div>
            <van-cell title="评论" :border="false" />

            <!-- 评论项 -->
            <van-cell
                v-for="(comment, index) in comments"
                :key="comment.id"
                :border="false"
            >
              <template #icon>
                <van-image
                    round
                    width="36px"
                    height="36px"
                    :src="comment.avatarResourcePath || defaultAvatar"
                    :alt="comment.userName"
                />
              </template>
              <template #title>
                <div class="comment-content" @click.stop>
                  <strong>{{ comment.userName }}</strong>
                  <p>{{ comment.content }}</p>
                  <div class="comment-footer">
                    <span class="comment-time">{{ formatDate(comment.createTime) }}</span>
                    <van-button
                        size="mini"
                        plain
                        type="primary"
                        @click.stop="toggleReplyInput(index)"
                        class="reply-btn"
                    >
                      回复
                    </van-button>
                    <!-- 删除按钮 - 只有评论作者或管理员可以删除 -->
                    <van-button
                        v-if="userStore.userInfo.userId === comment.commenterId || userStore.userInfo.userType === 3"
                        size="mini"
                        plain
                        type="danger"
                        @click.stop="confirmDelete(comment)"
                        :loading="deleteLoading"
                        class="delete-btn"
                    >
                      删除
                    </van-button>
                  </div>

                  <!-- 回复列表 -->
                  <div
                      v-if="comment.children && comment.children.length"
                      class="replies-container"
                  >
                    <div
                        v-for="(reply, replyIndex) in comment.children"
                        :key="reply.id"
                        class="reply-item"
                    >
                      <van-image
                          round
                          width="28px"
                          height="28px"
                          :src="reply.avatarResourcePath || defaultAvatar"
                          :alt="reply.userName"
                      />
                      <div class="reply-content">
                        <strong>{{ reply.userName }}</strong>
                        <span>回复</span>
                        <strong>{{ reply.replyToUserName || comment.userName }}</strong>
                        <p>{{ reply.content }}</p>
                        <span class="reply-time">{{ formatDate(reply.createTime) }}</span>
                        <van-button
                            v-if="(userStore.userInfo.userId === reply.commenterId || userStore.userInfo.userType === 3)"
                            size="mini"
                            plain
                            type="danger"
                            @click.stop="confirmDelete(reply)"
                            :loading="deleteLoading"
                            class="delete-btn"
                            style="margin-left: 8px;"
                        >
                          删除
                        </van-button>
                      </div>
                    </div>
                  </div>

                  <!-- 回复输入框 -->
                  <div v-if="activeReplyIndex === index" class="reply-input-container">
                    <van-field
                        v-model="replyContent"
                        placeholder="写下你的回复..."
                        :border="false"
                        size="small"
                        @click.stop
                    >
                      <template #button>
                        <van-button
                            size="mini"
                            type="primary"
                            @click.stop="submitReply(comment)"
                            :disabled="!replyContent.trim()"
                            :loading="replyLoading"
                        >
                          发送
                        </van-button>
                      </template>
                    </van-field>
                  </div>
                </div>
              </template>
            </van-cell>

            <!-- 加载更多 -->
            <div class="load-more" v-if="hasMore">
              <van-button
                  plain
                  type="primary"
                  size="small"
                  @click="loadMoreComments"
                  :loading="loadingMore"
              >
                加载更多评论
              </van-button>
            </div>
          </van-cell-group>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { computed } from "vue";
import { useTeachingPostStore } from "../../Store/modules/YRCG/EducationalAchievementArticle";
import { showDialog, showToast } from 'vant';
import { getCommentsByPostIdUsingGet, addCommentUsingPost, deleteCommentUsingGet  } from "../../Api/pinglunmokuai";
import type { Comment } from "../../Store/types/YRCG/TeachingPostComment";
import { useUserStore } from '../../Store/modules/userinfo/UserInfo'

const userStore = useUserStore()

const AchievementArticleStore = useTeachingPostStore();
const router = useRouter();
const title = computed(() => router.currentRoute.value.meta.title || "教学文章详情");

const item = AchievementArticleStore.fetchArticleDetail;

// 默认头像
const defaultAvatar = ref('https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg');

// 评论相关状态
const comments = ref<Comment[]>([]);
const newComment = ref('');
const replyContent = ref('');
const activeReplyIndex = ref(-1);
const commentLoading = ref(false);
const replyLoading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const hasMore = ref(true);
const loadingMore = ref(false);
const deleteLoading = ref(false);

// 初始化加载评论
onMounted(() => {
  loadComments();
});

// 加载评论
async function loadComments() {
  try {
    const response = await getCommentsByPostIdUsingGet({
      postId: item.articleId,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    });

    if (response.data.code === 0) {
      const newComments = response.data.data || [];
      if (currentPage.value === 1) {
        comments.value = newComments;
      } else {
        comments.value = [...comments.value, ...newComments];
      }
      hasMore.value = newComments.length >= pageSize.value;
    } else {
      throw new Error(response.data.message || '获取评论失败');
    }
  } catch (error: any) {
    showDialog({
      message: error.message || '获取评论失败，请重试！',
    });
  }
}

// 加载更多评论
async function loadMoreComments() {
  if (!hasMore.value) return;

  loadingMore.value = true;
  currentPage.value += 1;

  try {
    await loadComments();
  } finally {
    loadingMore.value = false;
  }
}

// 返回到教师交流
function goToYRCG() {
  router.push('/cqust/yrcg');
}

// 日期格式化
function formatDate(dateString: string) {
  if (!dateString) return '';
  const date = new Date(dateString);
  const now = new Date();

  // 如果是今天，显示时间
  if (date.toDateString() === now.toDateString()) {
    return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  }

  // 如果是今年，显示月日
  if (date.getFullYear() === now.getFullYear()) {
    return `${date.getMonth() + 1}月${date.getDate()}日`;
  }

  // 否则显示年月日
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
}

// 提交评论
async function submitComment() {
  if (!newComment.value.trim()) return;

  commentLoading.value = true;

  try {
    const response = await addCommentUsingPost({
      commenterId: userStore.userInfo.userId,
      content: newComment.value.trim(),
      id: 0,
      parentId: 0,
      postId: item.articleId,
      replyToUserId: item.authorId
    });

    if (response.data.code === 0) {
      showToast('评论发表成功');
      newComment.value = '';
      currentPage.value = 1;
      await loadComments();
    } else {
      throw new Error(response.data.message || '评论发表失败');
    }
  } catch (error: any) {
    showDialog({
      message: error.message || '评论发表失败，请重试！',
    });
  } finally {
    commentLoading.value = false;
  }
}

// 删除评论方法
async function deleteComment(commentId: number, isTopLevel: boolean) {
  try {
    deleteLoading.value = true;
    const response = await deleteCommentUsingGet({ commentId });

    if (response.data.code === 0) {
      showToast('删除成功');
      if (isTopLevel) {
        currentPage.value = 1;
        await loadComments();
      } else {
        updateCommentListAfterDelete(commentId);
      }
    } else {
      throw new Error(response.data.message || '删除失败');
    }
  } catch (error: any) {
    showDialog({
      message: error.message || '删除评论失败，请重试！',
    });
  } finally {
    deleteLoading.value = false;
  }
}

// 更新评论列表（删除回复后）
function updateCommentListAfterDelete(commentId: number) {
  comments.value = comments.value.map(comment => {
    if (comment.children) {
      return {
        ...comment,
        children: comment.children.filter(child => child.id !== commentId)
      };
    }
    return comment;
  });
}

// 确认删除对话框
function confirmDelete(comment: Comment) {
  showDialog({
    title: '确认删除',
    message: '确定要删除这条' + (comment.parentId === 0 ? '评论' : '回复') + '吗？',
    showCancelButton: true,
  }).then(() => {
    deleteComment(comment.id, comment.parentId === 0);
  }).catch(() => {
    // 用户取消
  });
}

// 切换回复输入框显示状态
function toggleReplyInput(index: number) {
  if (activeReplyIndex.value === index) {
    activeReplyIndex.value = -1;
  } else {
    activeReplyIndex.value = index;
    replyContent.value = '';
  }
}

// 处理外部点击事件
function handleOutsideClick() {
  activeReplyIndex.value = -1;
}

// 提交回复
async function submitReply(parentComment: Comment) {
  if (!replyContent.value.trim()) return;

  replyLoading.value = true;

  try {
    const response = await addCommentUsingPost({
      postId: item.articleId,
      content: replyContent.value.trim(),
      parentId: parentComment.id,
      replyToUserId: parentComment.commenterId,
      replyToUserName: parentComment.userName
    });

    if (response.data.code === 0) {
      showToast('回复成功');
      replyContent.value = '';
      activeReplyIndex.value = -1;
      await loadComments();
    } else {
      throw new Error(response.data.message || '回复失败');
    }
  } catch (error: any) {
    showDialog({
      message: error.message || '回复失败，请重试！',
    });
  } finally {
    replyLoading.value = false;
  }
}
</script>

<style scoped>
.header-with-back {
  height: 40px;
  background-color: #f8f8f8;
  padding: 10px;
  text-align: left;
  font-size: 20px;
  color: #682757;
  line-height: 40px;
  overflow: hidden;
  min-width: 100%;
  position: fixed;
  z-index: 999;
}

.back-nav {
  position: fixed;
  left: 1%;
  top: 1.25%;
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  color: rgb(83, 30, 88);
  padding: 0.5rem;
  z-index: 10;
  font-size: 0.9rem;
}

.header-with-back .van-icon {
  position: static;
  font-size: 1.35rem;
}

.content {
  padding-top: 18%;
  background-color: #f7f8fa;
  min-height: 100vh;
}

.img-container {
  padding: 16px 0;
}

.video-info {
  margin-bottom: 16px;
}

.video-title {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
  color: #323233;
}

:deep(.van-image) {
  padding-top: 1rem;
  padding-left: 5%;
  aspect-ratio: 16/9;
  object-fit: cover;
}

.bottom-van {
  border-top: #D9D6D6FC solid 2px;
}

.comments {
  margin-top: 16px;
}

.comment-content {
  padding-left: 12px;
}

.comment-content strong {
  font-size: 14px;
  color: #323233;
}

.comment-content p {
  margin: 4px 0;
  color: #666;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

:deep(.van-cell-group--inset) {
  margin: 0 16px;
}

:deep(.van-cell) {
  padding: 16px;
}

.comment-input-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 10px 16px;
  border-top: 1px solid #f5f5f5;
  z-index: 100;
}

.comment-footer {
  display: flex;
  align-items: center;
  margin-top: 8px;
}

.comment-time {
  font-size: 12px;
  color: #999;
  margin-right: 10px;
}

.reply-btn {
  height: 24px;
  line-height: 22px;
}

.replies-container {
  margin-top: 12px;
  padding-left: 12px;
  border-left: 2px solid #eee;
}

.reply-item {
  display: flex;
  margin-bottom: 12px;
}

.reply-content {
  margin-left: 8px;
  flex: 1;
}

.reply-content strong {
  font-size: 13px;
  color: #323233;
  margin-right: 4px;
}

.reply-content span {
  font-size: 12px;
  color: #999;
  margin-right: 4px;
}

.reply-content p {
  margin: 4px 0;
  font-size: 14px;
  color: #333;
}

.reply-time {
  font-size: 11px;
  color: #ccc;
  display: block;
}

.reply-input-container {
  margin-top: 10px;
  background-color: #f7f8fa;
  border-radius: 4px;
  padding: 8px;
}

:deep(.van-cell) {
  padding: 12px 16px;
}
.load-more {
  text-align: center;
  padding: 10px 0;
}
</style>
